package cn.algorithms_4ed.algo.sort;

import cn.stdlib.StdOut;

/**
 * 排序算法基类（工具类）
 * <p/>
 * User: erhu
 * Date: 13-6-15
 * Time: 上午10:19
 */
abstract class Sort {

    protected Comparable[] data;
    // 比较的次数
    protected int compareTimes;
    // 交换的次数
    protected int exchangeTimes;

    public Sort() {
        data = new String[]{"Z", "E", "B", "X", "G", "F", "Q", "D", "M"};
    }

    protected Sort resetData() {
        compareTimes = 0;
        exchangeTimes = 0;
        data = getData();
        return this;
    }

    public void setData(Comparable[] data) {
        //StdRandom.shuffle(data);
        this.data = data;
    }

    private Comparable[] getData() {
        return new String[]{"Z", "E", "B", "X", "G", "F", "Q", "D"};
    }

    protected boolean less(Comparable v, Comparable w) {
        compareTimes++;
        return v.compareTo(w) < 0;
    }

    protected void exchange(int i, int j) {
        if (i != j) {
            exchangeTimes++;
            Comparable tmp = data[i];
            data[i] = data[j];
            data[j] = tmp;
        }
    }

    protected void show() {
        for (Comparable item : data) {
            StdOut.print(item + " ");
        }
        StdOut.println();
        StdOut.println("------------------");
        StdOut.println("statics:");
        StdOut.println("data size     : " + data.length);
        StdOut.println("compare  times: " + compareTimes);
        StdOut.println("exchange times: " + exchangeTimes);
        StdOut.println("------------------");
        StdOut.println();
    }

    protected boolean isSorted() {
        for (int i = 1; i < data.length; i++) {
            if (less(data[i], data[i - 1]))
                return false;
        }
        return true;
    }

    abstract Sort sort();

    Sort sortFaster() {
        return this;
    }

    @Override
    public String toString() {
        return getClass().getSimpleName();
    }
}
